package org.mspring.mlog.service.impl;

import java.util.Date;

import org.mspring.mlog.entity.Album;
import org.mspring.mlog.entity.Photo;
import org.mspring.mlog.service.AlbumService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013-06-18 16:34:42
 */
@Service
@Transactional
public class AlbumServiceImpl extends GenericDao<Album, java.lang.Long> implements AlbumService {

    @Override
    public Album save(Album object) {
        // TODO Auto-generated method stub
        if (object.getCreateTime() == null) {
            object.setCreateTime(new Date());
        }
        return super.save(object);
    }

    @Override
    public int getAlbumPhotoCount(Long id) {
        // TODO Auto-generated method stub
        int count = 0;
        Object obj = getHibernateTemplate().uniqueResult("select count(*) from Photo photo where photo.album.id = ?", id);
        if (obj != null) {
            count = Integer.parseInt(obj.toString());
        }
        return count;
    }

    @Override
    public boolean hasPermission(Long albumId, String password) {
        // TODO Auto-generated method stub
        if (albumId == null) {
            return false;
        }
        Album album = get(albumId);
        if (Album.Type.PUBLIC.equals(album.getType())) {
            return true;
        } else if (Album.Type.PRIVATE.equals(album.getType())) {
            return false;
        } else if (password.equals(album.getVerifycode())) {
            return true;
        }
        return false;
    }

    @Override
    public void setCover(Long albumId, Long photoId) {
        // TODO Auto-generated method stub
        Album album = get(albumId);
        album.setCover(new Photo(photoId));
        update(album);
    }

}
